package com.example.controller;

import com.example.service.StampedLockCacheService;
import com.example.service.StampedLockCounterService;
import com.example.service.StampedLockExampleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/stamped/lock/example")
public class StampedLockExampleController {

    @Autowired
    private StampedLockExampleService service;

    @Autowired
    private StampedLockCacheService stampedLockCacheService;

    @Autowired
    private StampedLockCounterService stampedLockCounterService;

    // 乐观读操作接口
    @GetMapping("/optimistic-read")
    public String optimisticRead() {
        service.optimisticRead();
        return "StampedLock 乐观读操作已执行";
    }

    // 写操作接口
    @GetMapping("/write")
    public String write(@RequestParam int newValue) {
        service.write(newValue);
        return "StampedLock 写操作已执行";
    }

    // 缓存读取接口
    @GetMapping("/read-cache")
    public String readFromCache(@RequestParam String key) {
        String value = stampedLockCacheService.readFromCache(key);
        return "缓存读取到的值为: " + value;
    }

    // 缓存写入接口
    @GetMapping("/write-cache")
    public String writeToCache(@RequestParam String key, @RequestParam String value) {
        stampedLockCacheService.writeToCache(key, value);
        return "缓存数据成功: " + value;
    }

    // 增加计数器接口
    @GetMapping("/increment-counter")
    public String incrementCounter() {
        stampedLockCounterService.incrementCounter();
        return "计数器增加操作已执行";
    }

    // 获取计数器值接口
    @GetMapping("/get-counter")
    public String getCounter() {
        int value = stampedLockCounterService.getCounter();
        return "当前计数器值为: " + value;
    }
}
